package com.iwayin.core.bo.vote;

import com.iwayin.core.bo.BaseBO;
import com.iwayin.core.dao.answer.AnswerDAO;
import com.iwayin.core.dao.ask.AskDAO;
import com.iwayin.core.dao.vote.AnswerVoteDAO;
import com.iwayin.core.dataobject.AnswerVoteDO;
import com.iwayin.core.dataobject.AskDO;
import com.iwayin.core.utils.exception.BOException;

public class VoteBOImpl extends BaseBO implements VoteBO {

	private AnswerVoteDAO answerVoteDAO;
	private AnswerDAO answerDAO;
	private AskDAO askDAO;

	/*
	 * 1.检查有无投过票 2.没有直接添加 3.曾经投过，更新
	 */
	@Override
	public void addVote(AnswerVoteDO vote) {
		// 检测ask属性
		AskDO ask = askDAO.getAskById(vote.getAskId());
		if (ask == null || ask.getStatus().equals(0l)) {
			throw new BOException("问问已被删除");
		}
		if (ask.getStatus().equals(2l)) {
			throw new BOException("问问已被关闭");
		}
		AnswerVoteDO existObj = answerVoteDAO.getByAskIdUserId(vote);
		try {
			if (existObj == null) {
				answerVoteDAO.addAnswerVote(vote);
				askDAO.voteCountPlusOne(vote.getAskId());// 总投票+1
				answerDAO.answerVoteCountPlusOne(vote.getAnswerId());// 答案投票数+1
			} else {
				answerVoteDAO.updateVoteByAskIdUserId(vote);
				answerDAO.answerVoteCountDownOne(existObj.getAnswerId());
				answerDAO.answerVoteCountPlusOne(vote.getAnswerId());
			}
		} catch (Exception e) {
			loger.error("投票失败", e);
			throw new BOException();
		}
	}

	public void setAnswerVoteDAO(AnswerVoteDAO answerVoteDAO) {
		this.answerVoteDAO = answerVoteDAO;
	}

	public void setAnswerDAO(AnswerDAO answerDAO) {
		this.answerDAO = answerDAO;
	}

	public void setAskDAO(AskDAO askDAO) {
		this.askDAO = askDAO;
	}

}
